<template>
  <div class="car-status">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>车辆状态管理</span>
          <div class="header-operations">
            <el-input
              v-model="searchQuery"
              placeholder="搜索车辆品牌"
              style="width: 200px; margin-right: 10px"
            />
            <el-select v-model="statusFilter" placeholder="状态筛选" style="width: 120px">
              <el-option label="全部" value="" />
              <el-option label="可用" value="1" />
              <el-option label="已租" value="2" />
              <el-option label="维修中" value="3" />
            </el-select>
          </div>
        </div>
      </template>

      <el-table :data="filteredCarList" style="width: 100%">
        <el-table-column prop="id" label="车辆ID" width="100" />
        <el-table-column prop="brand" label="品牌" width="120" />
        <el-table-column prop="model" label="型号" width="120" />
        <el-table-column prop="plateNumber" label="车牌号" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastMaintenance" label="上次保养" width="180" />
        <el-table-column prop="nextMaintenance" label="下次保养" width="180" />
        <el-table-column prop="mileage" label="里程数" width="120" />
      </el-table>
      
      <!-- 添加分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 租出对话框 -->
    <el-dialog
      v-model="rentDialogVisible"
      title="车辆租出"
      width="500px"
    >
      <el-form :model="rentForm" label-width="100px" :rules="rentRules" ref="rentFormRef">
        <el-form-item label="客户" prop="customerId">
          <el-select v-model="rentForm.customerId" placeholder="请选择客户">
            <el-option
              v-for="customer in customerOptions"
              :key="customer.id"
              :label="customer.name"
              :value="customer.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker
            v-model="rentForm.startDate"
            type="datetime"
            placeholder="选择开始日期"
          />
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker
            v-model="rentForm.endDate"
            type="datetime"
            placeholder="选择结束日期"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRentSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 送修对话框 -->
    <el-dialog
      v-model="maintenanceDialogVisible"
      title="车辆送修"
      width="500px"
    >
      <el-form :model="maintenanceForm" label-width="100px" :rules="maintenanceRules" ref="maintenanceFormRef">
        <el-form-item label="维修原因" prop="reason">
          <el-input
            v-model="maintenanceForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入维修原因"
          />
        </el-form-item>
        <el-form-item label="预计完成" prop="estimatedDate">
          <el-date-picker
            v-model="maintenanceForm.estimatedDate"
            type="datetime"
            placeholder="选择预计完成日期"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="maintenanceDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleMaintenanceSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const carList = ref([])
const searchQuery = ref('')
const statusFilter = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 状态映射
const statusMap = {
  1: '可用',
  2: '已租',
  3: '维修中'
}

const filteredCarList = computed(() => {
  return carList.value.filter(car => {
    const matchSearch = car.brand.includes(searchQuery.value) || 
                       car.model.includes(searchQuery.value) ||
                       car.plateNumber.includes(searchQuery.value)
    const matchStatus = !statusFilter.value || Number(car.status) === Number(statusFilter.value)
    return matchSearch && matchStatus
  })
})

// 租出相关
const rentDialogVisible = ref(false)
const rentFormRef = ref(null)
const rentForm = reactive({
  customerId: '',
  startDate: '',
  endDate: ''
})

const rentRules = {
  customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }]
}

// 维修相关
const maintenanceDialogVisible = ref(false)
const maintenanceFormRef = ref(null)
const maintenanceForm = reactive({
  reason: '',
  estimatedDate: ''
})

const maintenanceRules = {
  reason: [{ required: true, message: '请输入维修原因', trigger: 'blur' }],
  estimatedDate: [{ required: true, message: '请选择预计完成日期', trigger: 'change' }]
}

// 模拟客户选项数据
const customerOptions = ref([
  { id: 1, name: '李四' },
  { id: 2, name: '王五' }
])

// 获取车辆列表
const fetchCarList = async () => {
  console.log('开始获取车辆列表...')
  try {
    const token = localStorage.getItem('Token')
    const url = new URL('http://localhost:8080/car/list')
    
    // 添加分页参数
    url.searchParams.append('page', currentPage.value)
    url.searchParams.append('size', pageSize.value)
    
    // 添加搜索参数
    if (searchQuery.value) {
      url.searchParams.append('brand', searchQuery.value)
    }
    
    // 添加状态筛选参数
    if (statusFilter.value) {
      url.searchParams.append('status', statusFilter.value)
    }

    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Token': token
      }
    })
    
    if (response.status === 401) {
      // token 过期或无效，清除本地存储并跳转到登录页
      localStorage.removeItem('Token')
      localStorage.removeItem('user')
      window.location.href = '/login'
      return
    }
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    console.log('获取车辆列表成功，原始数据：', result)
    
    if (result.code === 200) {
      // 处理返回的数据，确保status为数字类型
      carList.value = (result.data.records || []).map(car => ({
        ...car,
        status: Number(car.status),
        mileage: Number(car.mileage)
      }))
      total.value = result.data.total || 0
      currentPage.value = result.data.current || 1
      pageSize.value = result.data.size || 10
      console.log('处理后的车辆列表数据：', carList.value)
    } else {
      throw new Error(result.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取车辆列表失败：', error)
    ElMessage.error('获取车辆列表失败：' + error.message)
  }
}

// 监听搜索和筛选条件变化
watch([searchQuery, statusFilter], () => {
  currentPage.value = 1 // 重置页码
  fetchCarList()
})

// 处理页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchCarList()
}

// 处理每页条数改变
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchCarList()
}

// 在组件挂载时获取车辆列表
onMounted(() => {
  console.log('组件已挂载，准备获取车辆列表')
  fetchCarList()
})

const handleRent = (row) => {
  console.log('处理租出:', row)
  // 跳转到预定页面
  router.push('/reservation')
}

const handleRentSubmit = async () => {
  if (!rentFormRef.value) return
  
  await rentFormRef.value.validate((valid) => {
    if (valid) {
      // 这里添加租出逻辑
      ElMessage.success('车辆租出成功')
      rentDialogVisible.value = false
    }
  })
}

const handleMaintenance = (row) => {
  console.log('处理送修:', row)
  maintenanceDialogVisible.value = true
}

const handleMaintenanceSubmit = async () => {
  if (!maintenanceFormRef.value) return
  
  await maintenanceFormRef.value.validate((valid) => {
    if (valid) {
      // 这里添加送修逻辑
      ElMessage.success('车辆送修成功')
      maintenanceDialogVisible.value = false
    }
  })
}

const handleCompleteMaintenance = (row) => {
  console.log('处理完成维修:', row)
  ElMessageBox.confirm('确定完成该车辆的维修吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'success'
  }).then(() => {
    // 这里添加完成维修逻辑
    ElMessage.success('维修完成')
  })
}

const handleReturn = (row) => {
  console.log('处理归还:', row)
  ElMessageBox.confirm('确认该车辆已归还吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    try {
      const token = localStorage.getItem('Token')
      const response = await fetch(`http://localhost:8080/car/return/${row.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Token': token
        }
      })

      if (response.status === 401) {
        // token 过期或无效，清除本地存储并跳转到登录页
        localStorage.removeItem('Token')
        localStorage.removeItem('user')
        window.location.href = '/login'
        return
      }

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()
      if (result.code === 200) {
        ElMessage.success('车辆已归还')
        // 刷新列表
        fetchCarList()
      } else {
        throw new Error(result.message || '操作失败')
      }
    } catch (error) {
      console.error('归还失败：', error)
      ElMessage.error('归还失败：' + error.message)
    }
  }).catch(() => {
    // 用户取消操作
    ElMessage.info('已取消归还')
  })
}

// 获取状态类型
const getStatusType = (status) => {
  const statusTypeMap = {
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return statusTypeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  return statusMap[status] || '未知'
}
</script>

<style scoped>
.car-status {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-operations {
  display: flex;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 